package org.cloudlab.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.cloudlab.bean.SysUser;
import org.cloudlab.common.LoginUser;
import org.cloudlab.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 自定义用户登录类
 *
 * @author Liu Yicong
 * @date 2023/9/5
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private SysUserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//查询用户信息
		LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(SysUser::getUserName, username);
		SysUser user = userMapper.selectOne(queryWrapper);
		if (Objects.isNull(user)) {
			throw new UsernameNotFoundException("用户名不存在或者密码错误");
		}
		//如果用户数据正确, 那么更新一下最后的上线时间
		user.setLastLoginTime(new Date());
		userMapper.updateById(user);

		//把用户封装为UserDetails
		return new LoginUser(user);
	}
}
